from celery import shared_task
from mysqldb.weChatSDK import requests_Wechat_SDK
from mysqldb.models import AllinpayStaffList, AllinpayMemberList, GameLolUseropenidList
import xml.etree.ElementTree as ET
import json
import datetime
import logging


logger = logging.getLogger(__name__)


@shared_task
def DoCheckWeChatEvent(ment):
    """公众号回调消息处理函数"""

    def toDict(xml):
        try:
            root = ET.fromstring(f"""{xml}""")
        except BaseException as err:
            logger.warn(f"[xml] [pares] {err}")
            return None
        else:
            mdict = {}
            for child in root:
                mdict[child.tag] = child.text
            return mdict

    def toWeApi(openid):
        try:
            api = requests_Wechat_SDK()
            api.getConf()
            url = "/cgi-bin/user/info"
            headers = api.has_headers()
            params = {
                "access_token": api.has_access_token(),
                "openid": openid,
                "lang": "zh_CN ",
            }
            r = api.do_get(url=url, headers=headers, params=params)
            logger.info(f"[xml] [GET] {r}")
            return r
        except BaseException as err:
            logger.warn(f"[xml] [err] {err}")
            return None

    def bindStaff(mid, uid):
        # r,faq = AllinpayStaffList.objects.update_or_create(defaults={"mopenid":mid},unid=uid)
        try:
            res = AllinpayStaffList.objects.get(unid=uid)
        except BaseException as err:
            # logger.warn(f'[xml] [err] {err}')
            return None
        else:
            res.mopenid = mid
            res.save()
        """给用户打上员工标签"""
        try:
            api = requests_Wechat_SDK()
            api.getConf()
            url = "/cgi-bin/tags/members/batchtagging"
            headers = api.has_headers()
            params = {"access_token": api.has_access_token()}
            data = {"openid_list": [mid], "tagid": 100}
            r = api.do_post(
                url=url, headers=headers, params=params, data=json.dumps(data)
            )
            logger.info(f"[xml] [POST] {r}")
            return r
        except BaseException as err:
            logger.warn(f"[xml] [err] {err}")
            return None

    # 开始函数
    r = toDict(ment)
    if r:
        if r.get("MsgType") == "event":
            if (
                r.get("Event") == "view_miniprogram"
                and r.get("appid") == "wx5c86c1ae9599a236"
            ):
                """打上员工标签"""
                openid = r.get("FromUserName")
                res = toWeApi(openid)
                if not res:
                    return {"rescode": 555, "resmsg": "requesr is null"}
                if not 100 in res.get("tagid_list", []):
                    bindStaff(res.get("openid"), res.get("unionid"))
            elif r.get("Event") == "subscribe" or r.get("Event") == "SCAN":
                sess = eval(r.get("EventKey"))
                if sess.get("mid"):
                    """绑定会员微信公众号"""
                    # mid = int(r.get("EventKey")) if r.get("EventKey").isnumeric() else int(r.get("EventKey").split("_")[1])
                    try:
                        vip = AllinpayMemberList.objects.get(id=sess.get("mid"))
                    except BaseException as err:
                        logger.warn(f"[XML] [失败] [绑定会员微信公众号] {err}")
                    else:
                        vip.openid = r.get("FromUserName")
                        vip.save()
                if sess.get("userid"):
                    """绑定LOL账号"""
                    req, faq = GameLolUseropenidList.objects.update_or_create(
                        defaults={
                            "openid": r.get("FromUserName"),
                            "creatime": datetime.datetime.now(),
                        },
                        userid=sess.get("userid"),
                    )
            else:
                logger.debug(f"[xml] [未知事件类型] {r} ")
        else:
            logger.debug(f"[xml] [未知消息类型] {r} ")
    return {"rescode": 200, "resmsg": "ok"}
